﻿using Abp.Dependency;
using Abp.Domain.Uow;
using Abp.Events.Bus.Entities;
using Abp.Events.Bus.Handlers;
using Abp.Runtime.Caching;
using Mt.Site.Core.WorkFlows.Design.Entities;

namespace Mt.Site.Core.WorkFlows.Design.Cache
{
    public class WorkFlowCacheItemInvalidator :
        IEventHandler<EntityChangedEventData<WorkFlow>>,
        IEventHandler<EntityChangedEventData<WorkFlowNode>>,
        IEventHandler<EntityChangedEventData<WorkFlowForm>>,
        ITransientDependency
    {
        private readonly ICacheManager _cacheManager;

        public WorkFlowCacheItemInvalidator(ICacheManager cacheManager)
        {
            _cacheManager = cacheManager;
        }

        public void HandleEvent(EntityChangedEventData<WorkFlow> eventData)
        {
            var cacheKey = $"{eventData.Entity.Id}@{eventData.Entity.TenantId}";
            _cacheManager.GetWorkFlowCache().Remove(cacheKey);
        }

        public void HandleEvent(EntityChangedEventData<WorkFlowNode> eventData)
        {
            var cacheKey = $"{eventData.Entity.WorkflowId}@{eventData.Entity.TenantId}";
            _cacheManager.GetWorkFlowCache().Remove(cacheKey);
        }

        [UnitOfWork]
        public void HandleEvent(EntityChangedEventData<WorkFlowForm> eventData)
        {
            var cacheKey = $"{eventData.Entity.WorkFlowId}@{eventData.Entity.TenantId}";
            _cacheManager.GetWorkFlowCache().Remove(cacheKey);
        }
    }
}
